<?php
/**
 * 自动扣款
 * @author GRAY
 */

namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;
use Common\Vendor\Hook\BaseHook;
use Common\Library\SendSMS;
use Think\Cache\Driver\Redis;

class AutoPayController extends Controller {

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    private function  getOverDue($id, $consume_id){
        $overdue_amount = 0;
        $where = array("id"=>$id, "parent_id"=>$consume_id);
        $day=D("ConsumeInstallmentHistory")->field("overdue_amount , discount_percent ,id as install_id,amount as install_amount,add_time as inatall_add_time,repayment_time as install_repayment_time,discount_rebate,discount_percent,final_amount,discount")->where($where)->select();
        if($day && count($day)>0){
            $v = $day[0];
            $install_repayment_time = strtotime(date("Y-m-d 00:00:00",$v['install_repayment_time']));
            $overdue_day = (strtotime(date('Y-m-d',time()))-$install_repayment_time)/24/60/60;//每笔分期逾期天数

            if($overdue_day <= 0){
                $overdue_day = 0;
            }
            /*******final_amount***************/
            $fee_=$overdue_day>0?Constant::OVER_DATE_RATE:0;
            $overdue_amounts = $v['final_amount']>0?($v['final_amount']*100-$v['install_amount']):($v['install_amount']*$v['discount_percent']* Constant::Overdue_Interest_Rate  * $overdue_day+$fee_);
            if($overdue_amounts>$v['install_amount']){
                $overdue_amount=$v['install_amount'];
            }else{
                $overdue_amount=$overdue_amounts;
            }
        }
        return  $overdue_amount;
    }
    private function  getShengAmount($consume_id){
        $res=D("ConsumeHistory")->field("update_time,part_pay_amount,part_need_pay_amount,consume_amount")->where(['id'=>$consume_id])->find();
        //未还金额=（合同金额-已还金额）*2%*天数+未还金额
        //天数（当前时间-部分还款的时间）
        $res['update_time'] = strtotime(date("Y-m-d 00:00:00",$res['update_time']));
        $overday = (strtotime(date('Y-m-d',time()))-$res['update_time'])/24/60/60;
        if($overday>0){//划扣部分金额逾期的时间
            //本金-已还金额
            $amount=$res['consume_amount']-$res['part_pay_amount'];
            $weihuan=ceil($overday*($amount*Constant::Overdue_Interest_Rate))+Constant::OVER_DATE_RATE+$res['part_need_pay_amount'];
            if(($weihuan+$res['part_pay_amount'])>($res['consume_amount']*2)){
                $shengyu_amount=$res['consume_amount']*2-$res['part_pay_amount'];
            }else{
                $shengyu_amount=$weihuan;
            }
        }else if($overday==0){ //划扣部分金额当天又划扣未还金额，此时只划扣未还金额，不涉及逾期
            $shengyu_amount=$res['part_need_pay_amount']+Constant::OVER_DATE_RATE;
        }else if($res['part_pay_amount']>=$res['consume_amount']){ //已还大于等于合同，直接取剩余金额
            $shengyu_amount=$res['part_need_pay_amount'];
        }
        return  $shengyu_amount;
    }
    /************
     *
     * 后台点击划扣单个
     *
     ************/
    public function exepay() {
        try {
            $id = I('post.id', 0, 'int');
            $consume_id = I('post.consume_id', 0, 'int'); //消费ID
            $today = date('Ymd');
            $sql = "SELECT a.parent_id,b.type,b.customer_id,b.part_pay_amount,b.part_need_pay_amount,b.update_time,a.id,a.amount,a.repayment_time FROM `consume_installment_history` a
                    left join consume_history b on (b.id = a.parent_id)
                    WHERE a.id =  '$id' and a.parent_id ='$consume_id' and a.status =0
                    and b.type=5 and b.status=1
                    and b.customer_id in (SELECT c.`customer_id` FROM `customer_bank_info` c left join `customer` d on (d.id = c.`customer_id`) WHERE ( c.`usr_busi_agreement_id`<>'' or c.sub_contract_id <>'' ) and d.`id`>0 and d.`type`=1) order by b.customer_id limit 1";
            $result = M()->query($sql);
            if($result[0]['part_pay_amount']>0){
                Log::pay_write('++++++有部分还款，直接划扣剩余的金额|后台点击++++++++');
                if($result) {
                    $amount_shengyu=$this->getShengAmount($consume_id);
                    foreach($result as $v) {
                        $customer_id=$v['customer_id'];
                        $consume_id=$v['parent_id'];
                        $amount=$amount_shengyu;
                        $repay_date=$v['repayment_time'];
                        $kind=1;
                        $pay=A('Home/Pay');
                        Log::pay_write('**********后台划扣剩余金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                        $resultstatu = $pay->payConfirmPart($customer_id,$consume_id,$amount,$repay_date,$kind);
                        Log::pay_write('**********后台划扣剩余金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
                    }
                }
            }else{
                Log::pay_write('++++++没有部分还款，走原来逻辑还款|后台点击++++++++');
                if($result) {
                    $overdue_amount = $this->getOverDue($id, $consume_id);
                    foreach($result as $v) {
                        $customer_id=$v['customer_id'];
                        $consume_id=$v['parent_id'];
                        $amount=$overdue_amount+$v['amount'];
                        $repay_date=$v['repayment_time'];
                        $kind=1;
                        Log::pay_write('**********后台划扣全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                        $pay=A('Home/Pay');
                        $resultstatu = $pay->payConfirmPart($customer_id,$consume_id,$amount,$repay_date,$kind);
                        Log::pay_write('**********后台全部金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
                    }
                }
            }
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }


    /************
     *
     * 自动划扣功能|定时执行|当天到期客户|划扣全款|正向划扣
     *
     ************/
    public function autoexepay() {
        //sql查询需要划扣的客户
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            Log::pay_write('正向划扣token不过');
            die;
        }
        $begaim = strtotime(date('Y-m-d 00:00:00',time()));
        $end = strtotime(date('Y-m-d 23:59:59',time()));
        $redis = new Redis();
        $key = '正向划扣次数';
        $num = $redis->get($key);
        if(empty($num)){
            $redis->set($key,1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $begaim . '  AND ' . $end . '  ORDER BY a.id ASC LIMIT 1000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $customer_id=$val['customer_id'];
                $amount=$val['amount'];
                $repay_date=$val['repayment_time'];
                $kind=1;
                $pay=A('Home/Pay');
                Log::pay_write('**********定时正向划扣当天到期全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                $resultstatu = $pay->payConfirmPart($customer_id,$amount,$repay_date,$kind);
                Log::pay_write('**********当天到期正向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
            }
        }else{
            $n=700*$num;
            $redis->set($key,$redis->get($key)+1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $begaim . '  AND ' . $end . '  ORDER BY a.id ASC LIMIT ' . $n . ',1000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $customer_id=$val['customer_id'];
                $amount=$val['amount'];
                $repay_date=$val['repayment_time'];
                $kind=1;
                $pay=A('Home/Pay');
                Log::pay_write('**********定时正向划扣当天到期全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                $resultstatu = $pay->payConfirmPart($customer_id,$amount,$repay_date,$kind);
                Log::pay_write('**********当天到期正向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
            }
        }
    }

    /************
     *
     * 自动划扣功能|定时执行|当天到期客户|划扣全款|反向划扣
     *
     ************/
    public function autoexepays() {
        //sql查询需要划扣的客户
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            Log::pay_write('反向划扣token不过');
            die;
        }
        $begaim = strtotime(date('Y-m-d 00:00:00',time()));
        $end = strtotime(date('Y-m-d 23:59:59',time()));
        $redis = new Redis();
        $key = '反向划扣次数';
        $num = $redis->get($key);
        if(empty($num)){
            $redis->set($key,1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $begaim . '  AND ' . $end . '  ORDER BY a.id DESC LIMIT 1000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $customer_id=$val['customer_id'];
                $amount=$val['amount'];
                $repay_date=$val['repayment_time'];
                $kind=1;
                $pay=A('Home/Pay');
                Log::pay_write('**********定时反向划扣当天到期全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                $resultstatu = $pay->payConfirmPart($customer_id,$amount,$repay_date,$kind);
                Log::pay_write('**********当天到期反向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
            }
        }else{
            $n=700*$num;
            $redis->set($key,$redis->get($key)+1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $begaim . '  AND ' . $end . '  ORDER BY a.id DESC LIMIT ' . $n . ',1000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $customer_id=$val['customer_id'];
                $amount=$val['amount'];
                $repay_date=$val['repayment_time'];
                $kind=1;
                $pay=A('Home/Pay');
                Log::pay_write('**********定时反向划扣当天到期全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                $resultstatu = $pay->payConfirmPart($customer_id,$amount,$repay_date,$kind);
                Log::pay_write('**********当天到期反向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
            }
        }

    }

    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣全款|30天以内客户
     *
     ************/
    public function autoOverdue() {
        $filenames = C('LOG_PATH').date('Y-m-d',time()).'yuqihuakou'.'.log' ;
        if(file_exists($filenames)){
            unlink($filenames);
        }
        //sql查询需要划扣的客户
        $day1=strtotime(date("Y-m-d 23:59:59",time()))-86400;//逾期一天
        $day2=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
       $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $day2 . '  AND ' . $day1 . '  ORDER BY a.id desc';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $overdue_amount = $this->getOverDue($val['bid'], $val['id']);
                $customer_id=$val['customer_id'];
                $consume_id=$val['id'];
                $amount=$val['amount']+$overdue_amount;
                $repay_date=$val['repayment_time'];
                $kind=1;
                Log::pay_write('**********定时反向划扣逾期客户全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
                $arr=['customer_id'=>$customer_id,'consume_id'=>$consume_id,'amount'=>$amount,'repay_date'=>$repay_date,'kind'=>$kind];
                $redis= new Redis();
                $redis->set('yuqi-'.$customer_id,$arr,60*60*6);
                $filename =json_encode($customer_id) ;
                $filenameList = C('LOG_PATH').date('Y-m-d',time()).'yuqihuakou'.'.log' ;
                $filename .= "\n";
                $fileList=file_put_contents($filenameList, $filename, FILE_APPEND);//追加写入
            }
    }
    /***********
     **逾期真正请求交易中心
    ************/
    public function yuqiRealexect(){
        $arr1=I('get.customer_id');
        $arr2 = str_replace("&quot;"," ",$arr1);
        $redis= new Redis();
        $arr=$redis->get('yuqi-'.trim($arr2));
        $customer_id=$arr['customer_id'];
        $consume_id=$arr['consume_id'];
        $amount=$arr['amount'];
        $repay_date=$arr['repay_date'];
        $kind=$arr['kind'];
        $pay=A('Home/Pay');
        $resultstatu = $pay->payConfirmPart($customer_id,$consume_id,$amount,$repay_date,$kind);
        Log::pay_write('**********逾期反向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
    }
    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣全款|30天以内客户|正向
     *
     ************/
    public function autoOverduezheng() {
        //sql查询需要划扣的客户
        $day1=strtotime(date("Y-m-d 23:59:59",time()))-86400;//逾期一天
        $day2=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
        $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $day2 . '  AND ' . $day1 . '  ORDER BY a.id asc';
        $autopayArr = M()->query($sql);
        foreach($autopayArr as $key=>$val){
            $overdue_amount = $this->getOverDue($val['bid'], $val['id']);
            $customer_id=$val['customer_id'];
            $amount=$val['amount']+$overdue_amount;
            $repay_date=$val['repayment_time'];
            $kind=1;
            $pay=A('Home/Pay');
            Log::pay_write('**********定时正向划扣逾期客户全部金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
            $resultstatu = $pay->payConfirmPart($customer_id,$amount,$repay_date,$kind);
            Log::pay_write('**********逾期正向划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
        }

    }
    /************
     *
     * 自动划扣功能|定时执行|当天到期客户|划扣全款|全部一批划扣
     *
     ************/
    public function autoexepayzao() {
        $filenames = C('LOG_PATH').date('Y-m-d',time()).'todays'.'.log' ;
        if(file_exists($filenames)){
            unlink($filenames);
        }
        //sql查询需要划扣的客户
        $begaim = strtotime(date('Y-m-d 00:00:00',time()));
        $end = strtotime(date('Y-m-d 23:59:59',time()));
        $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,b.amount,a.customer_id FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.update_time=0
							  AND a.repayment_time
                BETWEEN ' . $begaim . '  AND ' . $end . '  ORDER BY a.id  DESC ';
        $autopayArr = M()->query($sql);
        foreach($autopayArr as $key=>$val){
            $customer_id=$val['customer_id'];
            $consume_id=$val['id'];
            $amount=$val['amount'];
            $repay_date=$val['repayment_time'];
            $kind=1;
            Log::pay_write('**********定时划扣当天到期全部用户金额|用户'.$customer_id.'金额'.$amount.'最后还款时间'.$repay_date);
            $arr=['customer_id'=>$customer_id,'consume_id'=>$consume_id,'amount'=>$amount,'repay_date'=>$repay_date,'kind'=>$kind];
            $redis= new Redis();
            $redis->set('today-'.$customer_id,$arr,60*60*6);
            $filename =json_encode($customer_id) ;
            $filenameList = C('LOG_PATH').date('Y-m-d',time()).'todays'.'.log' ;
            $filename .= "\n";
            $fileList=file_put_contents($filenameList, $filename, FILE_APPEND);//追加写入
        }
    }
    /**************
     *******当天到期的用户真正请求交易中心
    ********************/
    public function todayRealExepay(){
        $arr1=I('get.customer_id');
        $arr2 = str_replace("&quot;"," ",$arr1);
        $redis= new Redis();
        $arr=$redis->get('today-'.trim($arr2));
        $customer_id=$arr['customer_id'];
        $consume_id=$arr['consume_id'];
        $amount=$arr['amount'];
        $repay_date=$arr['repay_date'];
        $kind=$arr['kind'];
        $pay=A('Home/Pay');
        $resultstatu = $pay->payConfirmPart($customer_id,$consume_id,$amount,$repay_date,$kind);
        Log::pay_write('**********当天到期全部划扣金额|用户'.$customer_id.'请求业务层返回：'.$resultstatu.json_encode($resultstatu));
    }

    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣部分|30天以上客户
     ************/
    public function autoexepaybufen() {
        $filenames = C('LOG_PATH').date('Y-m-d',time()).'bufenhuakou'.'.log' ;
        if(file_exists($filenames)){
            unlink($filenames);
        }
        //sql查询需要划扣的客户
        $times=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,1)
							  AND  a.repayment_time < ' . $times . '
                ORDER BY a.id desc';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $redis= new Redis();
                $redis->set('parent-'.$val['parent_id'],$val,60*60*6);
                $filename =json_encode($val['parent_id']) ;
                $filenameList = C('LOG_PATH').date('Y-m-d',time()).'bufenhuakou'.'.log' ;
                $filename .= "\n";
                $fileList=file_put_contents($filenameList, $filename, FILE_APPEND);//追加写入
            }
    }

    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣部分|30天以上客户|正向查询
     ************/
    public function autoexepaybufenzheng() {
        //sql查询需要划扣的客户
        $times=strtotime(date("Y-m-d 23:59:59",time()))-2592000;//逾期三十天
        $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,1)
							  AND  a.repayment_time < ' . $times . '
                ORDER BY a.id asc';
        $autopayArr = M()->query($sql);
        foreach($autopayArr as $key=>$val){
            $this->partRepayAmountAction($val);
        }
    }

    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣部分|30-50
     ************/
    public function autoexepaybufen1() {
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            Log::pay_write('划扣30-50天token不过');
            die;
        }
        //sql查询需要划扣的客户
        $redis = new Redis();
        $key = '划扣部分金额次数30天以上';
        $num = $redis->get($key);
        if(empty($num)){
            $redis->set($key,1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,1)
							  AND  a.repayment_time BETWEEN 1508169600 AND 1510070400
                ORDER BY a.id desc limit 1000';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->partRepayAmountAction($val);
            }
        }else{
            $n=1000*$num;
            $redis->set($key,$redis->get($key)+1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,1)
							  AND  a.repayment_time BETWEEN 1508169600 AND 1510070400
                ORDER BY a.id desc limit ' . $n . ',1000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->partRepayAmountAction($val);
            }
        }
    }
    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣合同金额
     *
     ************/
    public function autoexepayOverdue() {
        //sql查询需要划扣的客户
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            Log::pay_write('划扣合同金额token不过');
            die;
        }
        $begaim = strtotime(date('Y-m-d 00:00:00',time()));
        $times = $begaim-86400;
        $redis = new Redis();
        $key = '逾期划扣合同金额次数_';
        $num = $redis->get($key);
        if(empty($num)){
            $redis->set($key,1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,2)
							  AND a.repayment_time <= ' . $times . '
                ORDER BY a.id desc limit 2000';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->consumeRepayAmountAction($val);
            }
        }
        else{
            $n=2000*$num;
            $redis->set($key,$redis->get($key)+1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,2)
							  AND a.repayment_time  <=' . $times . '
                 ORDER BY a.id desc LIMIT ' . $n . ',2000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->consumeRepayAmountAction($val);
            }
        }
    }
    /************
     *
     * 自动划扣功能|定时执行|逾期客户|划扣到账金额|本金
     *
     ************/
    public function overduedaozhang() {
        //sql查询需要划扣的客户
        $token = I('get.token','','string');
        $tok = CheckToken($token);
        if ($tok == false){
            Log::pay_write('划扣到账金额token不过');
            die;
        }
        $begaim = strtotime(date('Y-m-d 00:00:00',time()));
        $times = $begaim-86400;
        $redis = new Redis();
        $key = '逾期划扣到账金额次数_';
        $num = $redis->get($key);
        if(empty($num)){
            $redis->set($key,1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,a.amount,a.consume_amount,b.id as bid ,b.parent_id,a.type,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,3)
							  AND a.repayment_time <= ' . $times . '
                ORDER BY a.id desc limit 2000';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->actualRepayAmountAction($val);
            }
        }
        else{
            $n=2000*$num;
            $redis->set($key,$redis->get($key)+1,14400);
            $sql = ' SELECT a.id,a.type,a.`status`,a.repayment_time,a.update_time,b.id as bid ,b.parent_id,a.type,a.amount,a.consume_amount,a.customer_id,a.update_time,a.part_pay_amount,a.part_need_pay_amount,a.add_time,a.typeof FROM consume_history  as a
								LEFT JOIN `consume_installment_history` as b
								on a.id=b.parent_id
                WHERE a.type=5 AND a.status=1 AND a.typeof in (0,3)
							  AND a.repayment_time  <=' . $times . '
                 ORDER BY a.id desc LIMIT ' . $n . ',2000 ';
            $autopayArr = M()->query($sql);
            foreach($autopayArr as $key=>$val){
                $this->actualRepayAmountAction($val);
            }
        }
    }

    //部分金额划扣
    public function partRepayAmountAction()
    {
        $arr1=I('get.parent_id');
        $arr2 = str_replace("&quot;"," ",$arr1);
        $redis= new Redis();
        $arr=$redis->get('parent-'.trim($arr2));
        //------------------------逻辑继续
        $discount_percent = 0.2;//划扣百分比
        $kind = 3;//还款类型 1 主动还款2 被动还款   3部分还款
        $typeof = 1;//部分金额typeof=1
        $consume_amount = $arr['consume_amount'];//100000
        $amount = $arr['amount'];//85000
        $repayment_time = $arr['repayment_time'];//11月14日//1510588800
        $add_time = $arr['add_time'];//11月1日//1509465601
        $update_time = $arr['update_time'];//0
        $part_pay_amount = $arr['part_pay_amount'];//0
        $part_need_pay_amount = $arr['part_need_pay_amount'];//0
        $customer_id = $arr['customer_id'];
        $consume_id = $arr['id'];
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|接收数据$arr|'. json_encode($arr) .'|++++++++');
        $now = strtotime(date("Y-m-d"));
        if ($repayment_time > $now) {//应还日期晚于11月15日的情况
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|接收数据$repayment_time不满足订单逾期条件return|'. $repayment_time .'|customer_id'. $customer_id .'++++++++');
            return ;
        }
        
        if ($part_pay_amount < $consume_amount) {
            if ($update_time != 0) {
                $overdue_day = ( strtotime((date("Y-m-d")) - strtotime(date("Y-m-d", $update_time)) ) / 86400);
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|update_time|'. $update_time .'|overdue_day|'. $overdue_day);
                
                //应还金额计算/之前划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            } else {
                $overdue_day = (strtotime(date('Y-m-d',time()) )-$repayment_time)/24/60/60;
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|update_time--------|'. $update_time .'|overdue_day|'. $overdue_day);
                //应还金额计算/之前未划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            }
            
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|customer_id|'. $customer_id .'|应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            if ($need_pay_amount > $consume_amount * 2) {
                $need_pay_amount = $consume_amount * 2;
            } else {
                $need_pay_amount = $need_pay_amount - Constant::OVER_DATE_RATE;
            }
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|customer_id|'. $customer_id .'|息不过本原则|实际最后应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            //划扣金额计算
            $huakou_amount = ($need_pay_amount * $discount_percent > $amount) ? $amount : ($need_pay_amount * $discount_percent);
        } else {
            $res = ($part_need_pay_amount + $part_pay_amount + Constant::OVER_DATE_RATE) > $consume_amount * 2;
            if ($res) {
                //息过本
                $huakou_amount = $part_need_pay_amount;
            } else {
                //当已还金额不小于合同金额后，只划扣剩余金额+50违约金
                $huakou_amount = $part_need_pay_amount + Constant::OVER_DATE_RATE;
            }
            
        }
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@部分划扣|customer_id|'. $customer_id .'本次划扣金额huakou_amount|'. $huakou_amount .'|++++++++');
            A("Home/Pay")->payConfirmPart($customer_id, $consume_id, $huakou_amount, $repayment_time, $kind, $typeof);

    }

    //合同金额划扣
    public function consumeRepayAmountAction($arr)
    {
        $kind = 3;//还款类型 1 主动还款2 被动还款   3部分还款
        $typeof = 2;//合同金额typeof=2
        $consume_amount = $arr['consume_amount'];//100000
        $amount = $arr['amount'];//85000
        $repayment_time = $arr['repayment_time'];//11月14日//1510588800
        $add_time = $arr['add_time'];//11月1日//1509465601
        $update_time = $arr['update_time'];//0
        $part_pay_amount = $arr['part_pay_amount'];//0
        $part_need_pay_amount = $arr['part_need_pay_amount'];//0
        $customer_id = $arr['customer_id'];
        $consume_id = $arr['id'];
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|接收数据$arr|'. json_encode($arr) .'|++++++++');
        
        if ($part_pay_amount < $consume_amount) {
            if ($update_time != 0) {
                $overdue_day = ( strtotime((date("Y-m-d")) - strtotime(date("Y-m-d", $update_time)) ) / 86400);
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|update_time|'. $update_time .'|overdue_day|'. $overdue_day);
                
                //应还金额计算/之前划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            } else {
                $overdue_day = (strtotime(date('Y-m-d',time()) )-$repayment_time)/24/60/60;
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|update_time--------|'. $update_time .'|overdue_day|'. $overdue_day);
                //应还金额计算/之前未划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            }
            
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|customer_id|'. $customer_id .'|应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            if ($need_pay_amount > $consume_amount * 2) {
                $need_pay_amount = $consume_amount * 2;
            } else {
                $need_pay_amount = $need_pay_amount - Constant::OVER_DATE_RATE;
            }
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|customer_id|'. $customer_id .'|息不过本原则|实际最后应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            //划扣合同金额
            $huakou_amount = $consume_amount;
        } else {
            $res = ($part_need_pay_amount + $part_pay_amount + Constant::OVER_DATE_RATE) > $consume_amount * 2;
            if ($res) {
                //息过本
                $huakou_amount = $part_need_pay_amount;
            } else {
                //当已还金额不小于合同金额后，只划扣剩余金额+50违约金
                $huakou_amount = $part_need_pay_amount + Constant::OVER_DATE_RATE;
            }
            
        }
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@合同金额划扣|customer_id|'. $customer_id .'本次划扣金额huakou_amount|'. $huakou_amount .'|++++++++');
            A("Home/Pay")->payConfirmPart($customer_id, $consume_id, $huakou_amount, $repayment_time, $kind, $typeof);

    }

    //到账金额划扣
    public function actualRepayAmountAction($arr)
    {
        $kind = 3;//还款类型 1 主动还款2 被动还款   3部分还款
        $typeof = 3;//到账金额typeof=3
        $consume_amount = $arr['consume_amount'];//100000
        $amount = $arr['amount'];//85000
        $repayment_time = $arr['repayment_time'];//11月14日//1510588800
        $add_time = $arr['add_time'];//11月1日//1509465601
        $update_time = $arr['update_time'];//0
        $part_pay_amount = $arr['part_pay_amount'];//0
        $part_need_pay_amount = $arr['part_need_pay_amount'];//0
        $customer_id = $arr['customer_id'];
        $consume_id = $arr['id'];
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|接收数据$arr|'. json_encode($arr) .'|++++++++');
        
        if ($part_pay_amount < $consume_amount) {
            if ($update_time != 0) {
                $overdue_day = ( strtotime((date("Y-m-d")) - strtotime(date("Y-m-d", $update_time)) ) / 86400);
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|update_time|'. $update_time .'|overdue_day|'. $overdue_day);
                
                //应还金额计算/之前划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            } else {
                $overdue_day = (strtotime(date('Y-m-d',time()) )-$repayment_time)/24/60/60;
                Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|update_time--------|'. $update_time .'|overdue_day|'. $overdue_day);
                //应还金额计算/之前未划扣过部分金额
                $need_pay_amount = ($consume_amount - $part_pay_amount) * Constant::Overdue_Interest_Rate * $overdue_day + Constant::OVER_DATE_RATE + (($part_need_pay_amount == 0) ? $consume_amount : $part_need_pay_amount);
            }
            
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|customer_id|'. $customer_id .'|应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            if ($need_pay_amount > $consume_amount * 2) {
                $need_pay_amount = $consume_amount * 2;
            } else {
                $need_pay_amount = $need_pay_amount - Constant::OVER_DATE_RATE;
            }
            Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|customer_id|'. $customer_id .'|息不过本原则|实际最后应还金额need_pay_amount|'. $need_pay_amount .'|++++++++');
            //划扣合同金额
            $huakou_amount = ($part_pay_amount > 0) ? ($consume_amount - $amount) : $amount;
        } else {
            $res = ($part_need_pay_amount + $part_pay_amount + Constant::OVER_DATE_RATE) > $consume_amount * 2;
            if ($res) {
                //息过本
                $huakou_amount = $part_need_pay_amount;
            } else {
                //当已还金额不小于合同金额后，只划扣剩余金额+50违约金
                $huakou_amount = $part_need_pay_amount + Constant::OVER_DATE_RATE;
            }
            
        }
        Log::pay_write('@@@@@@Mr_zhao1019@@@@@到账金额划扣|customer_id|'. $customer_id .'本次划扣金额huakou_amount|'. $huakou_amount .'|++++++++');
            A("Home/Pay")->payConfirmPart($customer_id, $consume_id, $huakou_amount, $repayment_time, $kind, $typeof);

    }


    function genSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);
        //1. 按key由a到z排序
        ksort($param);
        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = $this->genSign($value);
            }
        }
        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));

        //3. 拼接我们的服务秘钥，并md5加密
        //$sign = md5($paramString . 'secret@9maibei.com');
        $sign = md5($paramString . 'secret@huoyan.com');
        return $sign;
    }

    function curlPost($url,$xml_data) {
        $ch=curl_init($url); 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_data));
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        return $response;
        //print_r($response);
    }
}
